<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class Personnel extends Model
{
    /**
     * @title 获取公司名称
     * @return mixed
     */
    public function getCompanyNameAttr(){
        $company_id = $this->company_id;
        $name = (new Company())->where("id",$company_id)->value("title_cn");
        return $name;
    }

    /**
     * @title 获取身份名称
     * @return string
     */
    public function getIdcardNameAttr(){
        $name = "";
        switch ($this->idcard){
            case 1:
                $name = "原作者";
                break;
            case 2:
                $name = "制作者";
                break;
            case 3:
                $name = "声优";
                break;
        }
        return $name;
    }
    public function getWorkIdAttr($val){
        if($val){
            return explode(",",$val);
        }else{
            return [];
        }
    }

    /**
     * @param $uname
     * @param $idcard
     * @param string $jp_jp
     * @param int $company_id
     * @param string $work_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add($uname,$idcard,$jp_jp="",$company_id=0,$work_id=null){
        //先查找有没有这个人
        $hasin = (new self)->where("idcard",$idcard)->where("uname",$uname)->find();
        if(!$hasin){
            $this->save([
                "uname"=>$uname,
                "idcard"=>$idcard,
                "company_id"=>$company_id,
                "jp_jp"=>$jp_jp,
                "work_id"=>$work_id,
                "add_time"=>date('Y-m-d H:i:s')
            ]);
        }else{
            if($work_id){
                if(!in_array($work_id,$hasin->work_id)){
                    $hasingwork_id = $hasin->work_id;
                    $hasingwork_id[]=$work_id;
                    (new self)->where("id",$hasin->id)->update([
                        "work_id"=>implode(",",$hasingwork_id)
                    ]);
                }
            }
        }
    }
}
